package cc.ttiot.thread.dataCollectionThread;

import cc.ttiot.mapper.dao.ApproachingSwitchMsgMapper;
import cc.ttiot.mapper.domain.ApproachingSwitchMsg;
import cc.ttiot.mapper.utils.MybatisUtils;
import cc.ttiot.service.dataCollection.io.impl.ApproachingSwitchCollection;
import cc.ttiot.utils.TimeUtils;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import org.apache.ibatis.session.SqlSession;

import static cc.ttiot.enums.SystemConstant.CLOSE;
import static cc.ttiot.enums.SystemConstant.OPEN;

/**
 * @Description:
 * @Author :
 * @Version :
 * @Date :
 */
public class ApproachingSwitchCollectThread implements Runnable {

    //数据库初始化
    /*
         1) SqlSession类是线程不安全的，所以每个线程都要有个单独的SqlSession
         2) 下面这种sqlSessionFactory.openSession()的方式获取SqlSession对象默认事务autoCommit设为false，
            所以除了查询语句其他语句执行后要调用sqlSession.commit()方法提交事务
    */
    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final ApproachingSwitchMsgMapper asmMapper = sqlSession.getMapper(ApproachingSwitchMsgMapper.class);
    private final ApproachingSwitchMsg approachingSwitchMsg = new ApproachingSwitchMsg();

    public ApproachingSwitchCollectThread() {
        super();
    }

    @Override
    public void run() {
        ApproachingSwitchCollection approachingSwitchCollection = ApproachingSwitchCollection.getInstance();
        

        //获取接近开关输入引脚
        GpioPinDigitalInput approachingSwitchDigitalInput = approachingSwitchCollection.getApproachingSwitchDigitalInput();

        //创建并注册GPIO_04引脚监听器
        approachingSwitchDigitalInput.addListener(new GpioPinListenerDigital() {
            @Override
            public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {

                //在控制台上显示pin状态
                System.out.println(" APPROACHING_SWITCH_PIN状态改变: " + event.getPin() + " = " + event.getState());
                if (event.getState() == PinState.HIGH) {
                    System.out.println("防护门开启");
                } else {
                    System.out.println("防护门关闭");
                }

                //更新对象值
                if (event.getState() == PinState.HIGH) {
                    approachingSwitchMsg.setState(OPEN);
                } else {
                    approachingSwitchMsg.setState(CLOSE);
                }
                approachingSwitchMsg.setTime(TimeUtils.getMillisecondTime());

                //存入数据库
                asmMapper.insertSingle(approachingSwitchMsg);
                sqlSession.commit();
            }
        });
    }
}
